<?php
namespace Admin\Model;
use Think\Model;
/**
CREATE TABLE `art_examcenter` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  `fromprovince` varchar(45) NOT NULL,
  `forprovince` varchar(120) NOT NULL,
  `inuse` int(8) NOT NULL DEFAULT '0',
  `majors` varchar(120) NOT NULL DEFAULT '0',
  `start_time` int(20) DEFAULT '0' COMMENT 'The start time of exam',
  `end_time` int(20) DEFAULT '0' COMMENT 'The end time of exam',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
*/
class ExamcenterModel extends Model{
	private $_id;	// 考点唯一标识符
	private $_name;	// 考点名称
	private $_fromprovince;	// 考点所在省份，存储省份代码
	private $_forprovince;	// 考点接受考生的省份，可以是多个值，不同的值以，分割
	private $_majors;	// 考点支持的专业，可以是多个值，不同的值以逗号分割
	private $_inuse;	// 考点是否启用，0表示不启用，1表示启用，只有启用的考点才可以被考生选择
	private $province = array();	// 存储省份
	public function __construct(){
		$this->province = C('PROVINCE');
		parent::__construct();
	}

	public function addOne($name, $from, $for, $majors,$starttime,$endtime, $inuse = 0){
		$this->_name = $name;
		$this->_fromprovince = $from;
		$this->_inuse = $inuse;
		$this->parseForProvince($for);
		$this->parseForMajors($majors);
		$this->_start_time = $this->parseTime($starttime);
		$this->_end_time = $this->parseTime($endtime);
		return $this->add($this->convertData(false));
	}

	public function saveOne($id, $name, $from, $for, $majors, $starttime,$endtime,$inuse = 0){
		$this->_id = $id;
		$this->_name = $name;
		$this->_fromprovince = $from;
		$this->_inuse = $inuse;
		$this->_start_time = $this->parseTime($starttime);
		$this->_end_time = $this->parseTime($endtime);
		$this->parseForProvince($for);
		$this->parseForMajors($majors);
		$data = $this->convertData(true);
		return $this->save($data);
	}

	private function parseForProvince($for){	// 解析forprovince
		if(is_array($for)){
			$this->_forprovince = implode(',', $for);
		}
	}

	private function parseForMajors($majors){
		if(is_array($majors)){
			$this->_majors = implode(',', $majors);
		}
	}

	private function convertData($needid = false){	// 组装数据

		$res = array(
			'name'	=>	$this->_name,
			'fromprovince'	=>	$this->_fromprovince,
			'forprovince'	=>	$this->_forprovince,
			'majors'	=>	$this->_majors,
			'inuse'	=>	$this->_inuse,
			'start_time'	=>	$this->_start_time,
			'end_time'	=>	$this->_end_time,
		);
		if($needid == true){
			$res['id']	=	$this->_id;
		}

		return $res;
	}

	public function getOne($id){
		return $this->where(array('id'=>$id))->find();
	}

	public function getNameById($id){
		return $this->where(array('id'=>$id))->getField('name');
	}

	private function checkProvince(){	// 检查省份代码是否合法，此处略过

	}

	public function setOpen($id, $status){
		$data['inuse'] = $status;
		return $this->where(array('id'=>$id))->save($data);
	}

	private function parseTime($time){
		$tmp = explode('-', $time);
		if(is_array($tmp)){
			$res = mktime(23, 59, 0, $tmp[1], $tmp[2], $tmp[0]);
			if($res != false){
				return $res;
			}
		}
		return 0;
	}
}
